from django.contrib.auth.models import User
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

from rest_framework import serializers

from system_manage.models import RedisUser
from utils.crypt_pwd import CryptPwd
from utils.request_utils import save_login_log


class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):

    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        # Add custom claims
        token['username'] = user.username
        token['key'] = 'redis-admin'
        return token

    def validate(self, attrs):
        data = super().validate(attrs)
        data['token'] = data.pop('access')
        data['userName'] = self.user.username
        data['nickName'] = self.user.nickname if self.user.nickname  else self.user.username
        data['isSuperuser'] = self.user.is_superuser
        data['userID'] = self.user.id
        # 记录登录日志
        request = self.context.get("request")
        request.user = self.user
        # 往session中存储用户的加密后密码，用于基础平台webssh使用用户的个人账号登录用
        request.session['user'] = self.user.username
        request.session['passwd'] = CryptPwd().encrypt_pwd(attrs['password'])
        # save_login_log(request=request)
        # 自定义验证逻辑
        if not self.user.is_active:
            msg = 'User account is disabled.'
            raise serializers.ValidationError(msg)

        # 更多自定义逻辑...

        return {"code": 200, "msg": "请求成功", "data": data}


class CustomTokenObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer
